package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.WmNewsMessageConstants;
import com.heima.model.wemedia.dtos.WmListVoDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //检查参数
        dto.checkParam();
        //分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        //条件查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //状态查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //查询当前登录人的文章
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        page = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult((int) page.getPages(), (int) page.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws IOException, TesseractException, TemplateException {
        //条件判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或者修改文章
        WmNews wmNews = new WmNews();
        //拷贝属性
        BeanUtils.copyProperties(dto, wmNews);
        //存入封面图片
        List<String> imagesList = dto.getImages();
        if (imagesList.size() != 0) {
            String images = StringUtils.join(imagesList, ",");
            wmNews.setImages(images);
        }

        //当前封面类型type为自动-1
        if (dto.getType() == -1) {
            //暂时设置为null
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        //判断是否是草稿，如果是草稿结束当前方法
        if (dto.getStatus() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿，保存文章内容图片与素材的关系
        List<String> contentImage = getContentImage(dto.getContent());
        saveMaterialAndNews(contentImage, wmNews.getId(), (short) 0);

        //不是草稿，保存文章封面图片与素材的关系
        saveCoverImages(dto, wmNews, contentImage);
        //异步调用进行自动审核
        //wmNewsAutoScanService.autoScanNews(wmNews.getId());
        wmNewsTaskService.addNewsTask(wmNews.getId(), wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId, id);
        //删除关联的素材
        wmNewsMaterialMapper.delete(queryWrapper);
        //删除文章
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 上下架文章
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        //检查参数
        if (wmNewsDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(wmNewsDto.getId());

        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }
        //修改文章的enable
        if (wmNewsDto.getEnable() != null && wmNewsDto.getEnable() > -1 && wmNewsDto.getEnable() < 2) {
            LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(WmNews::getEnable, wmNewsDto.getEnable());
            updateWrapper.eq(WmNews::getId, wmNews.getId());
            update(updateWrapper);
            //发送消息通知article修改文章配置
            Map<String, Object> map = new HashMap<>();
            if (wmNews.getArticleId() != null) {
                //文章ID
                map.put("articleId", wmNews.getArticleId());
                //上下架的enable
                map.put("enable", wmNews.getEnable());
                //通知文章模块需改文章的配置信息
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSONObject.toJSONString(map));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面
     * type -1 1>=图片<3 设置为type=1
     * 图片>=3 多图
     * 图片=0
     *
     * @param dto
     * @param wmNews
     * @param contentImage
     */
    private void saveCoverImages(WmNewsDto dto, WmNews wmNews, List<String> contentImage) {
        List<String> images = dto.getImages();
        if (dto.getType() == -1) {
            //多图
            if (contentImage.size() >= 3) {
                wmNews.setType((short) 3);
                for (String s : contentImage) {
                    images.add(s);
                }
            } else if (contentImage.size() >= 1 && contentImage.size() < 3) {
                //单图
                wmNews.setType((short) 1);
                images.add(contentImage.get(0));
            } else {
                //无图
                wmNews.setType((short) 0);
            }
            //修改文章中的图片列表,使用逗号分隔
            if (images.size() != 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 处理文章内容图片与素材的关系
     *
     * @param contentImage
     * @param newId
     * @param type
     */
    private void saveMaterialAndNews(List<String> contentImage, Integer newId, Short type) {
        if (contentImage != null && !contentImage.isEmpty()) {
            List<Integer> materialIds = new ArrayList<>();
            for (String s : contentImage) {
                LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                //拿文章的url来查询ID
                lambdaQueryWrapper.eq(WmMaterial::getUrl, s);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                //素材不存在抛错
                if (wmMaterial == null) {
                    throw new CustomException(AppHttpCodeEnum.WM_REF_FAIL);
                }
                materialIds.add(wmMaterial.getId());
            }
            wmNewsMaterialMapper.saveRelations(materialIds, newId, type);
        }
    }

    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> getContentImage(String content) {
        List<String> list = new ArrayList<>();
        //把文本内容转化成map集合
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                //获取里面的value
                String value = (String) map.get("value");
                list.add(value);
            }
        }
        return list;
    }


    @Override
    public ResponseResult oneVo(Integer id) {
        WmNews byId = getById(id);
        return ResponseResult.okResult(byId);
    }

    @Override
    public ResponseResult listVo(WmListVoDto dto) {
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if (!"".equals(dto.getTitle())) {
            queryWrapper.eq(WmNews::getTitle, dto.getTitle());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        page = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult((int) page.getPages(), (int) page.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        System.out.println(wmNews);
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //用户id
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        //创建时间
        wmNews.setCreatedTime(new Date());
        //提交时间
        wmNews.setSubmitedTime(new Date());
        //默认上架
        wmNews.setEnable((short) 1);
        if (wmNews.getId() == null) {
            //保存
            save(wmNews);
        } else {
            //修改
            //删除文章和素材的关系
            queryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            //存入当前新素材
            updateById(wmNews);
        }

    }
}
